/**
 * 发布订阅模式监听注入
 * listeners: {
 *     // 路由 router事件
 *      router: beforeEach: [],
 *      router: afterEach: [],
 *      router: error: [],
 *     // api请求axios
 *      axios:loading:show: [],
 *      axios:loading:hide: [],
 *      axios:request:before: [],
 *      axios:request:error: [],
 *      axios:response: [],
 *      axios:response:error: [],
 * }
 */
class PubSub {
    // 定义listeners对象，用于存储事件监听器
    private listeners: Record<string, ((...args: any[]) => any)[]> = {};

    constructor() {
        this.listeners = {};
    }

    /**
     * 订阅事件
     * @param eventName 事件名称，默认为空字符串
     * @param listener 事件监听器函数
     */
    on(eventName: string = '', listener: (...args: any[]) => any): void {
        if (!this.listeners[eventName]) {
            this.listeners[eventName] = [];
        }
        this.listeners[eventName].push(listener);
    }

    /**
     * 取消订阅事件
     * @param eventName 事件名称，默认为空字符串
     * @param listener 事件监听器函数
     */
    off(eventName: string = '', listener: ((...args: any[]) => any) | null): void {
        if (!listener || !this.listeners[eventName]) {
            console.log('not on event ', eventName, 'or listener must be a function');
            return;
        }
        this.listeners[eventName].some((item, idx) => {
            if (item.name === listener.name) {
                this.listeners[eventName].splice(idx, 1);
                return true;
            }
            return false;
        });
    }

    /**
     * 发布事件
     * @param eventName 事件名称，默认为空字符串
     * @param args 传递给事件监听器的参数
     * @returns 事件监听器的返回值数组
     */
    emit(eventName: string = '', ...args: any[]): any[] {
        if (!this.listeners[eventName]) {
            console.log('not on event ', eventName);
            return [];
        }
        const results: any[] = [];
        this.listeners[eventName].forEach((listener) => {
            const res = listener.apply(this, args);
            if (res !== undefined) {
                results.push(res);
            }
        });
        return results;
    }
}

const pubsub = new PubSub();

export default pubsub;

// 导出事件名称常量
export const ROUTER_BEFOREEACH: string = 'router:beforeEach';
export const ROUTER_AFTEREACH: string = 'router:afterEach';
export const ROUTER_ERROR: string = 'router:error';
export const AXIOS_REQUEST_SEND: string = 'axios:request:send';
export const AXIOS_REQUEST_BEFORE: string = 'axios:request:before';
export const AXIOS_REQUEST_ERROR: string = 'axios:request:error';
export const AXIOS_RESPONSE: string = 'axios:response';
export const AXIOS_RESPONSE_ERROR: string = 'axios:response:error';
export const AXIOS_LOADING_SHOW: string = 'axios:loading:show';
export const AXIOS_LOADING_HIDE: string = 'axios:loading:hide';